//
//  MainViewController.m
//  liangyi
//
//  Created by 张水 on 16/12/13.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "MainViewController.h"
#import "HealthViewController.h"
#import "MadePlanViewController.h"
#import "ChangePwdViewController.h"
#import "MainListCell.h"
#import "MainCellModel.h"
#import "AppHeader.h"
#import "MineViewController.h"
#import "MainheadView.h"
#import "MyschemeHeadView.h"
#import "PlanModel.h"
#import "MyschemeModel.h"
#import "SchemeModel.h"
#import "VideoPlayViewController.h"
@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>

@property(strong, nonatomic)NSMutableArray *dataArr;

@property(nonatomic,strong) NSMutableArray *stageArr;

@property(nonatomic,strong) NSMutableArray *MainDataArr;

@property(strong, nonatomic)UITableView *tableView;

@property(nonatomic,strong) MainheadView *headView;

@property(nonatomic,strong) MyschemeHeadView *SchemeheadView;

@property(nonatomic,copy)NSString *operationTime;

@property(nonatomic,copy)NSString *pid;

@property(nonatomic,copy)NSString *backtime;

@property(nonatomic,strong) GFCalendarView *calendar;

@property(nonatomic,strong) UIView  *backView;

@end

@implementation MainViewController

static NSString *ID = @"cell";

-(void)viewDidLoad{
    
    [super viewDidLoad];
    [self setupNavigation];
    self.dataArr = [NSMutableArray array];
    self.stageArr = [NSMutableArray array];
    self.MainDataArr = [NSMutableArray array];
    [self initUI];

}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self loadData];
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    MineViewController *mineVc = (MineViewController *)tempAppDelegate.LeftSlideVC.leftVC;
    [mineVc updateNewData];
    [tempAppDelegate.LeftSlideVC setPanEnabled:YES];
    [self loadMainData];

    
}

-(void)loadMainData{
    NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
    if (userLogin.length == 0) {
        self.headView = [[MainheadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 160)];
        [self.headView getScrollImageNetwork];
        self.tableView.tableHeaderView = self.headView;
    }else{
      
        [self getMyschemeData];
        self.SchemeheadView = [[MyschemeHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 260)];
        self.SchemeheadView.backView.hidden = YES;
        self.SchemeheadView.collectionView.hidden = YES;
        self.SchemeheadView.sectionNO.hidden = YES;
        self.SchemeheadView.sectionNoDes.hidden = YES;
        self.SchemeheadView.BeginTrain.hidden = NO;
        [self.SchemeheadView.BeginTrain addTarget:self action:@selector(BeginTOTrain) forControlEvents:UIControlEventTouchUpInside];
        [self.SchemeheadView.ModeiScheme addTarget:self action:@selector(ModeiTimeActionDidclick) forControlEvents:UIControlEventTouchUpInside];
        self.tableView.tableHeaderView = self.SchemeheadView;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
}


-(void)setupNavigation{
    
    self.title = @"顶医";
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 25, 25);
    [leftButton setImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(showLeftAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    
}
-(void)initUI{
    
    BOOL isfirst = [[NSUserDefaults standardUserDefaults] boolForKey:@"first"];
    if (!isfirst){
        [GuideViewController show];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"first"];
    }
    
    self.view.backgroundColor = [UIColor ColorWithHex:@"#ecf1f2"];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = YES;
    [CommonMethod hiddleExtendCellFromTableview:_tableView];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MainListCell class] forCellReuseIdentifier:ID];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.backView.backgroundColor = [UIColor blackColor];
    self.backView.alpha = 0.4;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeSubViewAction)];
    [self.backView addGestureRecognizer:tapGesture];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
        return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if  (section == 0){
        return 0;
    }else{
        return  self.MainDataArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0){
        MainListCell *mainCell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        if (!mainCell) {
            mainCell = [mainCell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        mainCell.DescribeImg.image = [UIImage imageNamed:@"banner"];
        return mainCell;
    }else{
    
        MainListCell *mainCell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        if (!mainCell) {
            mainCell = [mainCell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        mainCell.cellModel = self.MainDataArr[indexPath.row];
        
        return mainCell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ){
        return 160;
    }else{
        return 125;
    }
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor ColorWithHex:@"#ecf1f2"];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor ColorWithHex:@"#ecf1f2"];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (section == 0){
        return 10;
    }else{
        return 5;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
    }else{
        HealthViewController *healthVC = [HealthViewController new];
        healthVC.mainModel = self.MainDataArr[indexPath.row];
        [self.navigationController pushViewController:healthVC animated:YES];
    }
}


-(void)showLeftAction{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (tempAppDelegate.LeftSlideVC.closed){
        [tempAppDelegate.LeftSlideVC openLeftView];
    }else {
        [tempAppDelegate.LeftSlideVC closeLeftView];
    }
}

-(void)BeginTOTrain{
    VideoPlayViewController  *vc = [VideoPlayViewController new];
    vc.dataArr = self.dataArr;
    if (self.dataArr.count == 0){
        [self.navigationController popToRootViewControllerAnimated:YES];
        return ;
    }
    recoveriesModel *model = self.dataArr[0];
    vc.titles = model.title;
    vc.videoUrl =  model.videoAddress;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)ModeiTimeActionDidclick{
    
    if (self.stageArr.count == 0){
        [CustomProgressHUD showSuccessWithStatus:@"您还没有定制方案"];
        return ;
    }
    
    [[[UIAlertView alloc]initWithTitle:@"确定修改方案么?" message:@"请您严格按照医师的指导执行您的训练计划，如若随意修改，可能会出现一些问题，请您慎重选择。" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] show ];
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0){
        
    }
    if (buttonIndex == 1){
        
        NSString *url = [BASEURL stringByAppendingString:kURL_delScheme];
        NSDictionary *dict = @{@"pid":self.pid};
        NSLog(@"%@",dict);
        NSString *jsonString = [NSString dictionaryToJson:dict];
        NSString *AESString = [NSString AES128Encrypt:jsonString];
        NSDictionary *parameters = @{@"parameters":AESString,
                                     @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
        [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
            NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
            NSInteger code = network.code.integerValue;
            NSLog(@"%@",network.dataObject);
            if (code == 0){
                [self loadMainData];
            }else{
                [CustomProgressHUD showErrorWithStatus:network.errorDescription];
            }
        } failure:^(id error) {
            [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
        }];
        
        
    }
}

-(void)removeSubViewAction{
    [self.calendar removeFromSuperview];
    [self.backView removeFromSuperview];
}

-(void)getMyschemeData{
    NSString *url = [BASEURL stringByAppendingString:kURL_MyPlain];
    NSDictionary *dict = @{@"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:dict success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            SchemeModel *allData = [SchemeModel mj_objectWithKeyValues:network.dataObject];
            [self.stageArr removeAllObjects];
            [self.stageArr addObjectsFromArray:allData.stageList];
            self.stageArr =  [MyschemeModel mj_objectArrayWithKeyValuesArray:self.stageArr];
            
            
            PlanModel *model = [PlanModel mj_objectWithKeyValues:allData.plan];
            self.pid = model.id;
            self.backtime = [NSString timeWithTimeIntervalString:model.operationTime];
            NSLog(@"%@",self.backtime);
            
            [self.SchemeheadView.ModeiTime setTitle:[NSString stringWithFormat:@"(手术时间:%@)",self.backtime] forState:UIControlStateNormal];
            
            [self.tableView reloadData];
            StageModel *stage = [StageModel mj_objectWithKeyValues:allData.stage];
            if (stage == nil){
                self.tableView.tableHeaderView = self.headView;
                [self.headView  getScrollImageNetwork];
//                [CustomProgressHUD showSuccessWithStatus:@"当前阶段没有训练内容,请您休息一下吧!"];
                return ;
            }
            [self.SchemeheadView loadMySchemeData:stage];
            
            [self.dataArr removeAllObjects];
            [self.dataArr addObjectsFromArray:stage.recoveries];
            self.dataArr = [recoveriesModel mj_objectArrayWithKeyValuesArray:self.dataArr];
            
            self.SchemeheadView.desLable.text = @"您已经定制了您的康复计划方案，请您先点击开始训练按钮完成你选择的康复计划。";
        }else{
//            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
//            self.headView.hidden = YES;
            self.headView = [[MainheadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 160)];
            [self.headView getScrollImageNetwork];
            self.tableView.tableHeaderView = self.headView;
            return;
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
    
}


-(void)loadData{
    
    NSString *url = [BASEURL stringByAppendingString:kURL_list];
    
    [AppNetwork requestWithPath:url parameters:nil success:^(id responseObject) {
        NSLog(@"123%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            if ([network.dataObject isKindOfClass:[NSArray class]]){
                NSArray *arr = [MainCellModel mj_objectArrayWithKeyValuesArray:network.dataObject];
                [self.MainDataArr removeAllObjects];
                [self.MainDataArr addObjectsFromArray:arr];
                self.MainDataArr = [MainCellModel mj_objectArrayWithKeyValuesArray:self.MainDataArr];
                [self.tableView reloadData];
            }else{
                [CustomProgressHUD showErrorWithStatus:network.errorDescription];
            }
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
    
}


- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

@end
